<template>
  <div class="contain-edit">
    <div class="header">
      <p>房源管理/编辑房源</p>
      <el-button class="link" type="primary">
        <router-link to="/houseList" style="color: #fff;">返回</router-link>
      </el-button>
    </div>
    <div class="main">
        <el-form :model="information" :rules="rules" ref="information" label-width="120px" class="">
          <el-form-item label="小区：" prop="gardenName">
            <el-input v-model="information.gardenName" placeholder="请输入"></el-input>

            <!--<el-select v-model="information.gardenName" placeholder="请选择" @change="handleAreaChange">-->
              <!--<el-option-->
                <!--v-for="item in buildingList"-->
                <!--:key="item.value"-->
                <!--:label="item.label"-->
                <!--:value="item.value">-->
              <!--</el-option>-->
            <!--</el-select>-->
          </el-form-item>
          <el-form-item label="单元：" prop="unitName">
            <el-input v-model="information.unitName" placeholder="请输入"></el-input>

            <!--<el-select v-model="information.unitName" placeholder="请选择" @change="handleUnitChange">-->
              <!--<el-option-->
                <!--v-for="item in unitList"-->
                <!--:key="item.value"-->
                <!--:label="item.label"-->
                <!--:value="item.value">-->
              <!--</el-option>-->
            <!--</el-select>-->
          </el-form-item>
          <el-form-item label="楼栋：" prop="buildName">
            <el-input v-model="information.buildName" placeholder="请输入"></el-input>

            <!--<el-select v-model="information.buildName" placeholder="请选择">-->
              <!--<el-option-->
                <!--v-for="item in buildList"-->
                <!--:key="item.value"-->
                <!--:label="item.label"-->
                <!--:value="item.value">-->
              <!--</el-option>-->
            <!--</el-select>-->
          </el-form-item>
          <el-form-item label="楼层：" prop="floor">
            <el-input v-model="information.floor" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="房间：" prop="roomNo">
            <el-input v-model="information.roomNo" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="房东：" prop="">
            <el-input v-model="information.landlordName" disabled="" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="户型：" prop="roomType">
            <el-select v-model="information.roomType" placeholder="请选择" @change="handleAreaChange">
              <el-option
                v-for="item in roomTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="地址：" prop="address">
            <el-input v-model="information.address" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="面积：" prop="area">
            <el-input v-model="information.area" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="朝向：" prop="toward">
            <el-select v-model="information.toward" placeholder="请选择">
              <el-option
                v-for="item in towardList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="公共配置：" prop="">
            <el-tag
              :key="tag"
              v-for="tag in commonAllocateList"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)">
              {{tag}}
            </el-tag>
            <el-input
              class="input-new-tag"
              v-if="inputVisible"
              v-model="inputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm"
              @blur="handleInputConfirm"
            >
            </el-input>
            <el-button v-else class="button-new-tag" size="small" @click="showInput">自定义添加</el-button>
          </el-form-item>
          <el-form-item label="房屋配置：" prop="">
            <ul class="house-allocate">
              <li v-for="(item, index) in houseAllocateList" :key="index">
                <el-checkbox v-model="item.checked">
                  <span>{{item.label}}</span>
                  <el-input :disabled="!item.checked" autosize type="textarea" style="width: 250px" v-model="item.value" placeholder="请输入" v-if="item.label == '其他'"></el-input>
                  <el-input :disabled="!item.checked" v-model="item.value" placeholder="请输入" v-else></el-input>
                </el-checkbox>
                <!--<el-input autosize type="textarea" style="width: 250px" v-model="item.value" placeholder="请输入" v-if="item.label == '其他'"></el-input>-->
                <!--<el-input v-model="item.value" placeholder="请输入" v-else></el-input>-->
              </li>
            </ul>
          </el-form-item>
          <el-form-item label="房源图：" prop="imagesKey">
            <el-upload  list-type="picture-card"
                        :action="upLoadUrl"
                        :file-list='fileShowList'
                        :on-remove="handleRemove"
                        :before-upload="beforePicsUpload"
                        :limit="4">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="房源介绍：" prop="">
          <el-input v-model="information.memo" placeholder="请输入"></el-input>
        </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('information')"  :loading="loading">发布</el-button>
            <el-button @click="$router.push('/houseList')">返回</el-button>
          </el-form-item>
        </el-form>
    </div>

  </div>
</template>

<script>
  let CONSTANT = require('../../constant/constant.js');
  let common = require("../../common.js");
  import $ from 'jquery'
  import $axios from 'axios'
  export default {
    data() {
      return {
        id:null,
        checked: true,
        upLoadUrl: "",
        imagesAttachmentList: [],
        fileShowList: [],
        houseAllocateList: [{
          checked: false,
          label: "空调",
          value: ""
        },{
          checked: false,
          label: "热水器",
          value: ""
        },{
          checked: false,
          label: "洗衣机",
          value: ""
        },{
          checked: false,
          label: "床",
          value: ""
        },{
          checked: false,
          label: "其他",
          value: ""
        }],
        otherAllocateList: [],
        information:{
          gardenName: "",
          unitName: "",
          buildName: "",
          roomNo:"",
          publicAllocate: "",
          otherAllocate: "",
          houseAllocate: "",
          imagesKey: "",
          roomType: "",
          toward: "",
          memo: "",
          area: "",
          floor: "",
          address: "",
        },
        rules: {
          gardenName: [
            { required: true, message: '请输入小区', trigger: 'blur' },
          ],
          unitName: [
            { required: true, message: '请输入单元', trigger: 'blur' },
          ],
          buildName: [
            { required: true, message: '请输入楼栋', trigger: 'blur' },
          ],
          address: [
            { required: true, message: '请输入地址', trigger: 'blur' },
          ],
          roomNo: [
            { required: true, message: '请输入房间', trigger: 'blur' },
          ],
          customHouseNo: [
            { required: true, message: '请输入房屋编号', trigger: 'blur' }
          ],
          floor: [
            { required: true, message: '请输入楼层', trigger: 'blur' }
          ],
          imagesKey: [
            { required: true, message: '请选择图片', trigger: 'blur' }
          ],
          deposit: [
            { required: true, message: '请输入押金', trigger: 'blur' }
          ],
          roomType: [
            { required: true, message: '请输入户型', trigger: 'blur' }
          ],
          toward: [
            { required: true, message: '请输入朝向', trigger: 'blur' }
          ],
          memo: [
            { required: true, message: '请输入房源介绍', trigger: 'blur' }
          ],
          area: [
            { required: true, message: '请输入面积', trigger: 'blur' }
          ],
          cleaningFee: [
            { required: true, message: '请输入清洁费', trigger: 'blur' }
          ],
          gasFee: [
            { required: true, message: '请输入燃气费', trigger: 'blur' }
          ],
          healthFee: [
            { required: true, message: '请输入卫生费', trigger: 'blur' }
          ],
          internetFee: [
            { required: true, message: '请输入宽带费', trigger: 'blur' }
          ],
          managementFee: [
            { required: true, message: '请输入物业管理费', trigger: 'blur' }
          ],
          electricRate: [
            { required: true, message: '请输入电费单价', trigger: 'blur' }
          ],
          waterRate: [
            { required: true, message: '请输入水费单价', trigger: 'blur' }
          ],
          dayRent: [
            { required: true, message: '请输入日租金', trigger: 'blur' }
          ],
          longRent: [
            { required: true, message: '请输入月租金', trigger: 'blur' }
          ],
          yearRent: [
            { required: true, message: '请输入年租金', trigger: 'blur' }
          ],
          publicAllocate: [
            { required: true, message: '请添加公共配置', trigger: 'blur' }
          ],
          houseAllocate: [
            { required: true, message: '请输入房屋配置', trigger: 'blur' }
          ],
          buildingId: [
            { required: true, message: '请选择楼栋', trigger: 'blur' }
          ],
        },
        loading: false,

        towardList: [{
          lable: "东",
          value: "东"
        },{
          lable: "南",
          value: "南"
        },{
          lable: "西",
          value: "西"
        },{
          lable: "北",
          value: "北"
        }],
        roomTypeList: [{
          label: "一室一厅",
          value: "一室一厅"
        },{
          label: "两室一厅",
          value: "两室一厅"
        },{
          label: "两室两厅",
          value: "两室两厅"
        },{
          label: "三室一厅",
          value: "三室一厅"
        },{
          label: "三室两厅",
          value: "三室两厅"
        },{
          label: "四室一厅",
          value: "四室一厅"
        },{
          label: "四室两厅",
          value: "四室两厅"
        },{
          label: "单间",
          value: "单间"
        }],
        commonAllocateList: [],
        inputVisible: false,
        inputValue: '',
        value: "",
        buildingList: [],
        unitList: [],
        buildList: [],
        areaId: "",
        unitId: "",
        identify: ""
      };
    },
    components:{
      'bg-editor':()=>import('../common/bg-editor.vue')
    },
    mounted() {
      this.identify = sessionStorage.getItem("identify");
      this.id  = this.$router.currentRoute.query.id;
      this.information.landlordName = sessionStorage.getItem("manager")
//      this.getBuildList(0, (data) => {
//        data.map( item => {
//          this.buildingList.push({
//            label: item.name,
//            value: item.id
//          })
//        })
//      })
      this.getGardenList()
      if(this.id){
        this.getDetail();
      }
    },
    methods: {
      getBuildList(id, callback = null) {
        let url = this.identify == 1 ? CONSTANT.URL.BUILDING.FINDLIST : CONSTANT.URL.L_BUILDING.FINDLIST,
          params = {
            parentId: id
          }
          common.requestAjax(url, JSON.stringify(params), {}, (data) => {
             if (data.status ==200) {
               callback && callback(data.data.bussData)
             }
          })
      },
      getGardenList() {
        let url = CONSTANT.URL.L_HOUSE.L_GARDEN;
        common.requestAjax(url, {}, {}, (data) => {
          if (data.status ==200) {
            data.data.bussData.map( item => {
              this.buildingList.push({
                label: item,
                value: item
              })
            })
          }
        })
      },
      getUnitList() {
        let url = CONSTANT.URL.L_HOUSE.L_UNIT;
        common.requestAjax(url, {}, {gardenName: this.information.gardenName}, (data) => {
          if (data.status ==200) {
            data.data.bussData.map( item => {
              this.unitList.push({
                label: item,
                value: item
              })
            })
          }
        })
      },
      getBuildingList() {
        let url = CONSTANT.URL.L_HOUSE.L_BUILD;
        common.requestAjax(url, {}, {unitName: this.information.unitName}, (data) => {
          if (data.status ==200) {
            data.data.bussData.map( item => {
              this.buildList.push({
                label: item,
                value: item
              })
            })
          }
        })
      },
      getDetail(){
        let url = this.identify == 1 ? CONSTANT.URL.HOUSE.DETAIL : CONSTANT.URL.L_HOUSE.DETAIL;
        let data = {
          id:this.id
        } ;
        common.requestAjax(url, {}, data, (res)=>{
          let d = res.data.bussData;
          let houseAllocate = d.houseAllocate ? d.houseAllocate : null, otherAllocate = d.otherAllocate ? d.otherAllocate : null, publicAllocate = d.publicAllocate ? d.publicAllocate : null, images = d.images ? d.images : []
          this.houseAllocateList[4].value = otherAllocate;
          this.houseAllocateList[4].checked = otherAllocate ? true : false
          this.houseAllocateList.map( (item1, index1) => {
            if (houseAllocate) {
              houseAllocate.split(",").map( (item, index) => {
                let itemSplit = item.split(":")
                if (itemSplit[0] == item1.label) {
                  this.houseAllocateList[index1].value = itemSplit[1]
                  this.houseAllocateList[index1].checked = true
                }
              })
            }
          })

          this.commonAllocateList = publicAllocate ? publicAllocate.split(",") : []
          images.map( (item, index) => {
            images[index] = {url: item}
          })
          this.fileShowList = images

          this.information = {
            roomNo: d.roomNo,
            gardenName: d.gardenName,
            unitName: d.unitName,
            buildName: d.buildName,
            publicAllocate: d.publicAllocate,
            otherAllocate: d.otherAllocate,
            houseAllocate: d.houseAllocate,
            imagesKey: d.imagesKey,
            roomType: d.roomType,
            toward: d.toward,
            memo: d.memo,
            floor: d.floor,
            area: d.area,
          }
        })
      },
      getBuildingDetail(id) {
        let url = CONSTANT.URL.L_BUILDING.DETAIL;
        common.requestAjax(url, {}, {id: id}, (result) => {
          if (result.status == 200) {
            this.unitId = result.data.bussData.parent.id;
            this.areaId = result.data.bussData.parent.parent.id

            this.getBuildList(this.unitId, (data) => {
              data.map( item => {
                this.buildList.push({
                  label: item.name,
                  value: item.id
                })
              })
            })
            this.getBuildList(this.areaId, (data) => {
              data.map( item => {
                this.unitList.push({
                  label: item.name,
                  value: item.id
                })
              })
            })
          }
        })
      },

      submitForm(formName) {
        let filter = this.houseAllocateList.filter( item => {
          return item.checked
        })
//        if (filter.length == 0) {
//          this.$message({
//            type: "warning",
//            message: "请补充完整房屋配置"
//          })
//          return false
//        }

        this.houseAllocateList.map( (item, index) => {
          if (item.checked && !item.value) {
            this.$message({
              type: "warning",
              message: "请补充完整房屋配置"
            })
            return false
          }
        })

        let houseAllocateList = filter.filter( item => { //(item.value || item.value == 0)
          return  item.label != "其他"
        })
        let otherAllocateList = filter.filter( item => {
          return item.label == "其他"
        })

        filter.map( (item, index) => {
          houseAllocateList[index] = item.label+":"+item.value
        })

        this.information.houseAllocate = houseAllocateList.join(",")
        this.information.otherAllocate = otherAllocateList.length ? otherAllocateList[0].value : ""

        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.loading = true;
            if(this.id){
              var url = this.identify == 1 ? CONSTANT.URL.HOUSE.UPDATE : CONSTANT.URL.L_HOUSE.UPDATE;
            }else{
              var url = this.identify == 1 ? CONSTANT.URL.HOUSE.ADD : CONSTANT.URL.L_HOUSE.ADD;
            }
            let param = JSON.stringify(Object.assign(this.information, {id: this.id ? this.id : ''}));
            common.requestAjax(url, param, null, res => {
              if(res.status == 200) {
                this.$message({
                  type: 'success',
                  message: '保存成功!'
                });
                this.loading = false;
                this.$router.push("/houseList");
              } else {
                this.$message({
                  type: 'error',
                  message: res.msg
                });
                this.loading = false;
              }
            });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      beforePicsUpload(file) {
        let url =CONSTANT.URL.COMMON.UPLOAD;
        let param = {
          suffix:file.name.split(".")[1],   // 文件后缀  png
          contentType:file.type             // 文件类型  image/png
        }
        common.requestAjax(url,param,null,(res)=> {
          this.upLoadUrl = res.data.bussData.uploadUrl;
          this.imagesAttachmentList.push(res.data.bussData.fileKey)
          this.information.imagesKey = this.imagesAttachmentList.join(",")
          let downloadUrl = res.data.bussData.downloadUrl;
          common.uploadFile(this.upLoadUrl,file,file.type,(res)=>{
            this.fileShowList.push({
              url:downloadUrl
            })
          })
        });
      },
      handleRemove(file, fileList) {
        this.information.imagesKey = []
        let arr = []
        fileList.map( (item, index) => {
          arr.push(item.url.split("com/")[1])
        })
        this.information.imagesKey = arr.join(",")
      },

      handleClose(tag) {
        this.commonAllocateList.splice(this.commonAllocateList.indexOf(tag), 1);
        this.information.publicAllocate = this.commonAllocateList.join(",")
      },

      showInput() {
        this.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },

      handleInputConfirm() {
        let inputValue = this.inputValue;
        if (inputValue) {
          this.commonAllocateList.push(inputValue);
          this.information.publicAllocate = this.commonAllocateList.join(",")
        }
        this.inputVisible = false;
        this.inputValue = '';
      },
      handleAreaChange() {
        this.getUnitList()
      },
      handleUnitChange() {
        this.getBuildingList()
      }
    }
  }
</script>

<style lang="scss" scoped >
  @import '/static/bootstrap.css';
  @import '/sys/static/bootstrap.css';
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  ul, li {
    list-style: none;
  }
  .house-allocate {
    li {
      margin-bottom: 20px;
      span {
        width: 60px;
        display: inline-block;
      }
    }
  }
  .el-form-item__content{
    margin-left: 0;
  }
  .avatar-uploader {
    border-radius: 6px;
    box-sizing: border-box;
    vertical-align: top;
    .el-upload {
      cursor: pointer;
      position: relative;
      overflow: hidden;
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
        border: 1px dashed #d9d9d9 !important;
        border-radius: 6px;
        margin-left: 6px;
      }
      .avatar {
        width: 178px;
        height: 178px;
        display: block;
      }
    }
    .el-upload:hover {
      border-color: #20a0ff;
    }
  }
</style>
